<template>
  <div class="hotel-week-summary">
    <div class="top-section" style="display: flex; align-items: center; justify-content: space-between; padding: 12px 12px ;">
      <div class="header-wrapper" style="margin-bottom: 0;">
        <h3 class="title">
          周报经营数据-
          <span :class="['acc-title-span', { active: currentAcc === 'day' }]">当天</span>/
          <span :class="['acc-title-span', { active: currentAcc === 'month' }]">当月</span>/
          <span :class="['acc-title-span', { active: currentAcc === 'year' }]">当年</span>累计
        </h3>
      </div>
      <div class="form-wrapper" style="margin-bottom: 0; display: flex; align-items: center; gap: 8px;">
        <div class="form-content" style="display: flex; align-items: center; gap: 8px;">
          <div v-if="isAcc" class="acc-selector">
            <img
              :src="daySvg"
              alt="day"
              class="button-icon"
             
              :title="'看当天'"
              :class="{ active: currentAcc === 'day' }"
              @click="handleAccChange('day')"
            />
            <img
              :src="monthSvg"
              alt="month"
              class="button-icon"
              :title="'看当月'"
              :class="{ active: currentAcc === 'month' }"
              @click="handleAccChange('month')"
            />
            <img
              :src="yearSvg"
              alt="year"
              class="button-icon"
              :title="'看当年'"
              :class="{ active: currentAcc === 'year' }"
              @click="handleAccChange('year')"
            />
          </div>
          <div class="form-item">
            
            <a-range-picker
              v-model:value="currentRange"
              :placeholder="['开始日期', '结束日期']"
              style="width: 260px"
              :open="rangePickerOpen"
              @openChange="onRangeOpenChange"
            >
              <template #suffixIcon>
                <calendar-outlined />
              </template>
              <template #renderExtraFooter>
                <div style="text-align: right; padding: 4px">
                  <a-button size="small" type="primary" @click="onRangeOk">确定</a-button>
                </div>
              </template>
            </a-range-picker>
          </div>
          <div class="form-item form-item-center" style="flex: 1; display: flex; align-items: center; justify-content: flex-end; min-width: 120px;">
            <a-switch
              v-model:checked="isDetail"
              style="margin-right: 0; width: 110px; min-width: 100px; vertical-align: middle;"
            >
              <template #checkedChildren>
                <span style="display: inline-block; width: 80px; text-align: center; font-size: 12px; color: #fff;">显示缩略列</span>
              </template>
              <template #unCheckedChildren>
                <span style="display: inline-block; width: 80px; text-align: center; font-size: 12px; color: #666;">查看全部列</span>
              </template>
            </a-switch>
          </div>
          <!-- <div class="form-item">
            <div class="filter-icon-container">
              <img class="icon-screen" src="/@/assets/images/screening.png" @click="handleShowFilter" alt="筛选图标" :title="'过滤设置'" />
            </div>
          </div> -->
        </div>
      </div>
    </div>
    <div class="main-content">
      <a-card type="default">
        <div class="card-table-head">
          实际收入周报
          <div class="card-table-head-remark">
            <a-button type="link" class="ant-btn-icon-only" @click="handleExport">
              <template #icon>
                <download-outlined />
              </template>
            </a-button>
          </div>
        </div>
        <div class="card-table-content">
          <div class="table-scroll-x">
            <table class="fixed-width-table">
              <thead>
                <tr>
                  <th rowspan="3"   class="fixed-table-head">项目名称</th>
                  <th :colspan="isDetail ? 3 : 10" style="background:#E9E7F2;">本周实际</th>
                  <th :colspan="isDetail ? 3 : 10" style="background:#E9E7F2;">去年同期</th>
                  <th :colspan="isDetail ? 3 : 8" style="background:#E9E7F2;">差异</th>
                </tr>
                <tr class="head-layer2">
                  <!-- 本周实际 -->
                  <template v-if="!isDetail">
                    <th>已售房间夜</th>
                    <th>可售房间夜</th>
                  </template>
                  <th>出租率</th>
                  <th>平均房价</th>
                  <template v-if="!isDetail">
                    <th>每房收益</th>
                    <th>客房收入</th>
                    <th>餐厅收入</th>
                    <th>宴会收入</th>
                    <th>其他收入</th>
                  </template>
                  <th>总收入</th>

                  <!-- 去年同期 -->
                  <template v-if="!isDetail">
                    <th>已售房间夜</th>
                    <th>可售房间夜</th>
                  </template>
                  <th>出租率</th>
                  <th>平均房价</th>
                  <template v-if="!isDetail">
                    <th>每房收益</th>
                    <th>客房收入</th>
                    <th>餐厅收入</th>
                    <th>宴会收入</th>
                    <th>其他收入</th>
                  </template>
                  <th>总收入</th>

                  <!-- 差异 -->
                  <th>出租率</th>
                  <th>平均房价</th>
                  <template v-if="!isDetail">
                    <th>每房收益</th>
                    <th>客房收入</th>
                    <th>餐厅收入</th>
                    <th>宴会收入</th>
                    <th>其他收入</th>
                  </template>
                  <th>总收入</th>
                </tr>
                <tr class="head-layer2">
                  <!-- 本周实际 -->
                  <template v-if="!isDetail">
                    <th>间夜</th>
                    <th>间夜</th>
                  </template>
                  <th>%</th>
                  <th>元</th>
                  <template v-if="!isDetail">
                    <th>元</th>
                    <th>元</th>
                    <th>元</th>
                    <th>元</th>
                    <th>元</th>
                  </template>
                  <th>万元</th>

                  <!-- 去年同期 -->
                  <template v-if="!isDetail">
                    <th>间夜</th>
                    <th>间夜</th>
                  </template>
                  <th>%</th>
                  <th>元</th>
                  <template v-if="!isDetail">
                    <th>元</th>
                    <th>元</th>
                    <th>元</th>
                    <th>元</th>
                    <th>元</th>
                  </template>
                  <th>万元</th>

                  <!-- 差异 -->
                  <th>%</th>
                  <th>元</th>
                  <template v-if="!isDetail">
                    <th>元</th>
                    <th>元</th>
                    <th>元</th>
                    <th>元</th>
                    <th>元</th>
                  </template>
                  <th>万元</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="item in dataList" :key="item.key">
                  <td   class="fixed-table-head">{{ item.hotelName }}</td>
                  <!-- 本周实际 -->
                  <template v-if="!isDetail">
                    <td style="text-align: center;">{{ item.actualSrooms }}</td>
                    <td style="text-align: center;">{{ item.actualCrooms }}</td>
                  </template>
                  <td style="text-align: center;">{{ percent2DFormatter(item.actualRentRate) }}</td>
                  <td style="text-align: center;">{{ currencyWNFormatter(item.actualPrice) }}</td>
                  <template v-if="!isDetail">
                    <td style="text-align: center;">{{ currencyWNFormatter(item.actualPerRevenue) }}</td>
                    <td style="text-align: center;">{{ currencyWNFormatter(item.roomRevenue) }}</td>
                    <td style="text-align: center;">{{ currencyWNFormatter(item.fbRevenue) }}</td>
                    <td style="text-align: center;">{{ currencyWNFormatter(item.bhRevenue) }}</td>
                    <td style="text-align: center;">{{ currencyWNFormatter(item.otherRevenue) }}</td>
                  </template>
                  <td style="text-align: center;">{{ currencyWNFormatter(item.revenue) }}</td>

                  <!-- 去年同期 -->
                  <template v-if="!isDetail">
                    <td style="text-align: center;">{{ item.lyearActualSrooms }}</td>
                    <td style="text-align: center;">{{ item.lyearActualCrooms }}</td>
                  </template>
                  <td style="text-align: center;">{{ percent2DFormatter(item.lyearRentRate) }}</td>
                  <td style="text-align: center;">{{ currencyWNFormatter(item.lyearPrice) }}</td>
                  <template v-if="!isDetail">
                    <td style="text-align: center;">{{ currencyWNFormatter(item.lyearPerRevenue) }}</td>
                    <td style="text-align: center;">{{ currencyWNFormatter(item.lyearRoomRevenue) }}</td>
                    <td style="text-align: center;">{{ currencyWNFormatter(item.lyearFbRevenue) }}</td>
                    <td style="text-align: center;">{{ currencyWNFormatter(item.lyearBhRevenue) }}</td>
                    <td style="text-align: center;">{{ currencyWNFormatter(item.lyearOtherRevenue) }}</td>
                  </template>
                  <td style="text-align: center;">{{ currencyWNFormatter(item.lyearRevenue) }}</td>

                  <!-- 差异 -->
                  <td style="text-align: center;">{{ item.diffRentRate }}</td>
                  <td style="text-align: center;">{{ item.diffPrice }}</td>
                  <template v-if="!isDetail">
                    <td style="text-align: center;">{{ item.diffPerRevenue }}</td>
                    <td style="text-align: center;">{{ item.diffRoomRevenue }}</td>
                    <td style="text-align: center;">{{ item.diffFbRevenue }}</td>
                    <td style="text-align: center;">{{ item.diffBhRevenue }}</td>
                    <td style="text-align: center;">{{ item.diffOtherRevenue }}</td>
                  </template>
                  <td style="text-align: center;">{{ item.diffRevenue }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </a-card>
    </div>
  </div>
  <SearchFilterModal v-if="showFilter" v-model:visible="showFilter" :fields="searchFormOptions" :visible="showFilter" @save="handleSaveFilter" />
</template>
<script>
  import dayjs from 'dayjs';
  import * as MathUtil from '/@/utils/MathUtil';
  import * as DateUtil from '/@/utils/dateUtil';
  import { DatePicker, Switch, Button, Card, Table, Skeleton } from 'ant-design-vue';
  import { defHttp } from '/@/utils/http/axios';
  import { CalendarOutlined, CalendarTwoTone, DownloadOutlined } from '@ant-design/icons-vue';
  import SearchFilterModal from '/@/views/applications/ui/SearchFilterModal.vue';
  import { onMounted, nextTick } from 'vue';
  import monthSvg from '/@/assets/svg/month-svg.svg';
  import yearSvg from '/@/assets/svg/year-svg.svg';
  import daySvg from '/@/assets/svg/day-svg.svg';
  import * as XLSX from 'xlsx-js-style';
  const SUM_FIELDS = [
    'actualSrooms',
    'actualCrooms',
    'roomRevenue',
    'fbRevenue',
    'bhRevenue',
    'otherRevenue',
    'revenue',
    'lyearActualSrooms',
    'lyearActualCrooms',
    'lyearRoomRevenue',
    'lyearFbRevenue',
    'lyearBhRevenue',
    'lyearOtherRevenue',
    'lyearRevenue',
  ];

  const DETAIL_COLS = [
    'actualSrooms',
    'actualCrooms',
    'actualPerRevenue',
    'roomRevenue',
    'fbRevenue',
    'bhRevenue',
    'otherRevenue',
    'lyearActualSrooms',
    'lyearActualCrooms',
    'lyearPerRevenue',
    'lyearRoomRevenue',
    'lyearFbRevenue',
    'lyearBhRevenue',
    'lyearOtherRevenue',
    'diffActualSrooms',
    'diffActualCrooms',
    'diffPerRevenue',
    'diffRoomRevenue',
    'diffFbRevenue',
    'diffBhRevenue',
    'diffOtherRevenue',
  ];

  export default {
    name: 'HotelWeekSummary',

    components: {
      ARangePicker: DatePicker.RangePicker,
      ASwitch: Switch,
      AButton: Button,
      CalendarOutlined,
      CalendarTwoTone,
      DownloadOutlined,
      SearchFilterModal,
      ACard: Card,
      ATable: Table,
      ASkeleton: Skeleton,
    },

    data() {
      return {
        rangePickerOpen: false,
        showFilter: false,
        hotelList: [],
        currentHotel: {
          code: '',
          name: '',
        },
        loading: false,
        tableHigh: { x: '100%', y: 'calc(60vh)' },
        isDetail: true,
        currentRange: [this.previousThursday(), this.lastThursday()],
        dataList: [],
        dataColumns: [
          {
            title: '项目名称',
            dataIndex: 'hotelName',
            key: 'hotelName',
            width: 220,
            align: 'left',
            ellipsis: true,
            fixed: 'left',
            scopedSlots: {
              customRender: 'hotelName',
            },
          },
          {
            dataIndex: 'actualSrooms',
            width: 105,
            align: 'right',
            children: [
              {
                title: '已售房间夜',
                dataIndex: 'actualSrooms',
                key: 'actualSrooms',
                width: 105,
                align: 'right',
                customRender: (val) => this.dot2Formatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'actualCrooms',
            width: 105,
            align: 'right',
            children: [
              {
                title: '可售房间夜',
                dataIndex: 'actualCrooms',
                key: 'actualCrooms',
                width: 105,
                align: 'right',
                customRender: (val) => this.dot2Formatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'actualRentRate',
            width: 105,
            align: 'right',
            children: [
              {
                title: '出租率',
                dataIndex: 'actualRentRate',
                key: 'actualRentRate',
                width: 105,
                align: 'right',
                customRender: (val) => this.percent2DFormatter(val.text, 0),
              },
            ],
          },
          {
            title: '本周实际',
            dataIndex: 'actualPrice',
            width: 105,
            align: 'right',
            children: [
              {
                title: '平均房价',
                dataIndex: 'actualPrice',
                key: 'actualPrice',
                width: 105,
                align: 'right',
                customRender: (val) => this.dot2Formatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'actualPerRevenue',
            width: 105,
            align: 'right',
            children: [
              {
                title: '每房收益',
                dataIndex: 'actualPerRevenue',
                key: 'actualPerRevenue',
                width: 105,
                align: 'right',
                customRender: (val) => this.dot2Formatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'roomRevenue',
            width: 105,
            align: 'right',
            children: [
              {
                title: '客房收入',
                dataIndex: 'roomRevenue',
                key: 'roomRevenue',
                width: 105,
                align: 'right',
                customRender: (val) => this.currencyWNFormatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'fbRevenue',
            width: 105,
            align: 'right',
            children: [
              {
                title: '餐厅收入',
                dataIndex: 'fbRevenue',
                key: 'fbRevenue',
                width: 105,
                align: 'right',
                customRender: (val) => this.currencyWNFormatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'bhRevenue',
            width: 105,
            align: 'right',
            children: [
              {
                title: '宴会收入',
                dataIndex: 'bhRevenue',
                key: 'bhRevenue',
                width: 105,
                align: 'right',
                customRender: (val) => this.currencyWNFormatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'otherRevenue',
            width: 105,
            align: 'right',
            children: [
              {
                title: '其他收入',
                dataIndex: 'otherRevenue',
                key: 'otherRevenue',
                width: 105,
                align: 'right',
                customRender: (val) => this.currencyWNFormatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'revenue',
            width: 105,
            align: 'right',
            children: [
              {
                title: '总收入',
                dataIndex: 'revenue',
                key: 'revenue',
                width: 105,
                align: 'right',
                customRender: (val) => this.currencyWNFormatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'lyearActualSrooms',
            width: 105,
            align: 'right',
            className: 'table-header-color',
            children: [
              {
                title: '已售房间夜',
                dataIndex: 'lyearActualSrooms',
                key: 'lyearActualSrooms',
                width: 105,
                align: 'right',
                className: 'table-header-color',
                customRender: (val) => this.dot2Formatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'lyearActualCrooms',
            width: 105,
            align: 'right',
            className: 'table-header-color',
            children: [
              {
                title: '可售房间夜',
                dataIndex: 'lyearActualCrooms',
                key: 'lyearActualCrooms',
                width: 105,
                align: 'right',
                className: 'table-header-color',
                customRender: (val) => this.dot2Formatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'lyearRentRate',
            width: 105,
            align: 'right',
            className: 'table-header-color',
            children: [
              {
                title: '出租率',
                dataIndex: 'lyearRentRate',
                key: 'lyearRentRate',
                width: 105,
                align: 'right',
                className: 'table-header-color',
                customRender: (val) => this.percent2DFormatter(val.text, 0),
              },
            ],
          },
          {
            title: '去年同期',
            dataIndex: 'lyearPrice',
            width: 105,
            align: 'right',
            className: 'table-header-color',
            children: [
              {
                title: '平均房价',
                dataIndex: 'lyearPrice',
                key: 'lyearPrice',
                width: 105,
                align: 'right',
                className: 'table-header-color',
                customRender: (val) => this.dot2Formatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'lyearPerRevenue',
            width: 105,
            align: 'right',
            className: 'table-header-color',
            children: [
              {
                title: '每房收益',
                dataIndex: 'lyearPerRevenue',
                key: 'lyearPerRevenue',
                width: 105,
                align: 'right',
                className: 'table-header-color',
                customRender: (val) => this.dot2Formatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'lyearRoomRevenue',
            width: 105,
            align: 'right',
            className: 'table-header-color',
            children: [
              {
                title: '客房收入',
                dataIndex: 'lyearRoomRevenue',
                key: 'lyearRoomRevenue',
                width: 105,
                align: 'right',
                className: 'table-header-color',
                customRender: (val) => this.currencyWNFormatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'lyearFbRevenue',
            width: 105,
            align: 'right',
            className: 'table-header-color',
            children: [
              {
                title: '餐厅收入',
                dataIndex: 'lyearFbRevenue',
                key: 'lyearFbRevenue',
                width: 105,
                align: 'right',
                className: 'table-header-color',
                customRender: (val) => this.currencyWNFormatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'lyearBhRevenue',
            width: 105,
            align: 'right',
            className: 'table-header-color',
            children: [
              {
                title: '宴会收入',
                dataIndex: 'lyearBhRevenue',
                key: 'lyearBhRevenue',
                width: 105,
                align: 'right',
                className: 'table-header-color',
                customRender: (val) => this.currencyWNFormatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'lyearOtherRevenue',
            width: 105,
            align: 'right',
            className: 'table-header-color',
            children: [
              {
                title: '其他收入',
                dataIndex: 'lyearOtherRevenue',
                key: 'lyearOtherRevenue',
                width: 105,
                align: 'right',
                className: 'table-header-color',
                customRender: (val) => this.currencyWNFormatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'lyearRevenue',
            width: 105,
            align: 'right',
            className: 'table-header-color',
            children: [
              {
                title: '总收入',
                dataIndex: 'lyearRevenue',
                key: 'lyearRevenue',
                width: 105,
                align: 'right',
                className: 'table-header-color',
                customRender: (val) => this.currencyWNFormatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'diffRentRate',
            width: 105,
            align: 'right',
            children: [
              {
                title: '出租率',
                dataIndex: 'diffRentRate',
                key: 'diffRentRate',
                width: 105,
                align: 'right',
              },
            ],
          },
          {
            title: '差异',
            dataIndex: 'diffPrice',
            width: 105,
            align: 'right',
            children: [
              {
                title: '平均房价',
                dataIndex: 'diffPrice',
                key: 'diffPrice',
                width: 105,
                align: 'right',
              },
            ],
          },
          {
            dataIndex: 'diffPerRevenue',
            width: 105,
            align: 'right',
            children: [
              {
                title: '每房收益',
                dataIndex: 'diffPerRevenue',
                key: 'diffPerRevenue',
                width: 105,
                align: 'right',
              },
            ],
          },
          {
            dataIndex: 'diffRoomRevenue',
            width: 105,
            align: 'right',
            children: [
              {
                title: '客房收入',
                dataIndex: 'diffRoomRevenue',
                key: 'diffRoomRevenue',
                width: 105,
                align: 'right',
              },
            ],
          },
          {
            dataIndex: 'diffFbRevenue',
            width: 105,
            align: 'right',
            children: [
              {
                title: '餐厅收入',
                dataIndex: 'diffFbRevenue',
                key: 'diffFbRevenue',
                width: 105,
                align: 'right',
              },
            ],
          },
          {
            dataIndex: 'diffBhRevenue',
            width: 105,
            align: 'right',
            children: [
              {
                title: '宴会收入',
                dataIndex: 'diffBhRevenue',
                key: 'diffBhRevenue',
                width: 105,
                align: 'right',
              },
            ],
          },
          {
            dataIndex: 'diffOtherRevenue',
            width: 105,
            align: 'right',
            children: [
              {
                title: '其他收入',
                dataIndex: 'diffOtherRevenue',
                key: 'diffOtherRevenue',
                width: 105,
                align: 'right',
              },
            ],
          },
          {
            dataIndex: 'diffRevenue',
            width: 105,
            align: 'right',
            children: [
              {
                title: '总收入',
                dataIndex: 'diffRevenue',
                key: 'diffRevenue',
                width: 105,
                align: 'right',
              },
            ],
          },
        ],
        exportHeader: [
          [
            '项目名称',
            '本周实际',
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            '去年同期',
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            '差异',
            null,
            null,
            null,
            null,
            null,
            null,
            null,
          ],
          [
            null,
            '已售房间夜',
            '可售房间夜',
            '出租率',
            '平均房价',
            '每房收益',
            '客房收入',
            '餐厅收入',
            '宴会收入',
            '其他收入',
            '总收入',
            '已售房间夜',
            '可售房间夜',
            '出租率',
            '平均房价',
            '每房收益',
            '客房收入',
            '餐厅收入',
            '宴会收入',
            '其他收入',
            '总收入',
            '出租率',
            '平均房价',
            '每房收益',
            '客房收入',
            '餐厅收入',
            '宴会收入',
            '其他收入',
            '总收入',
          ],
        ],
        pageHeader: {
          collapsed: true,
          title: '酒店周报',
          formProrps: {
            layout: 'horizontal',
          },
          formOptions: [
            {
              label: '时段',
              slotName: 'dateslot',
            },
            {
              label: '展示详细列',
              slotName: 'detailslot',
            },
          ],
        },
        searchFormOptions: [
          {
            value: 'date',
            label: '时段',
            selected: true,
            showDetails: true,
          },
          {
            value: 'detail',
            label: '展示详细列',
            selected: true,
            showDetails: true,
          },
        ],
        selectedFields: [],
        isAcc: true,
        currentAcc: 'year',
        monthSvg,
        yearSvg,
        daySvg,
      };
    },

    created() {
      defHttp.get({ url: '/data/hotel/list' }, { isTransformResponse: false }).then((res) => {
        if (res.code === 200 && res.result.length > 0) {
          this.currentHotel = { code: res.result.map((d) => d.code).join(',') };
          this.hotelList = res.result;
          this.fetchBaseInfo();
        }
      });
    },

    mounted() {
      this.$nextTick(() => {
        setTimeout(() => {
            const ths = document.querySelectorAll('th.ant-table-cell');
          ths.forEach(th => {
            // 根据 title 或文本内容判断
        
              th.style.backgroundColor = '#000 !important;';
              th.style.color = '#fff !important;'; 
        
          });
        },1000);
      
      });
    },

    methods: {
      onRangeOpenChange(open) {
        this.rangePickerOpen = open;
      },
      onRangeOk() {
        console.log('确定按钮点击，当前日期范围:', this.currentRange);
        console.log(this.currentRange[0].format('YYYY-MM-DD'),this.currentRange[1].format('YYYY-MM-DD'))
        this.rangePickerOpen = false;
        this.fetchBaseInfo();
      },
      handleShowFilter() {
        this.showFilter = true;
      },

      handleSaveFilter(updatedFields) {
        this.selectedFields = updatedFields;
        this.searchFormOptions = updatedFields;

        // 更新表单显示
        const dateField = updatedFields.find((f) => f.value === 'date');
        const detailField = updatedFields.find((f) => f.value === 'detail');

        // 根据选择的字段更新表单显示
        this.$nextTick(() => {
          const formWrapper = document.querySelector('.form-wrapper');
          if (formWrapper) {
            const dateItem = formWrapper.querySelector('.form-item:nth-child(1)');
            const detailItem = formWrapper.querySelector('.form-item:nth-child(2)');

            if (dateItem) {
              dateItem.style.display = dateField?.selected ? 'flex' : 'none';
            }
            if (detailItem) {
              detailItem.style.display = detailField?.selected ? 'flex' : 'none';
            }
          }
        });

        // 重新查询数据
        this.fetchBaseInfo();
      },
      fetchBaseInfo() {
        this.loading = true;
        defHttp
          .post({
            url: '/data/query',
            data: {
              labelCode: 'getHotelDailySummary',
              params: [],
              sqlParams: [
                {
                  key: 'code',
                  value: this.currentHotel.code,
                },
                {
                  key: 'beginDate',
                  value: this.currentRange[0].format('YYYY-MM-DD'),
                },
                {
                  key: 'endDate',
                  value: this.currentRange[1].format('YYYY-MM-DD'),
                },
                {
                  key: 'beginContrastDate',
                  value: 'x',
                },
                {
                  key: 'endContrastDate',
                  value: 'x',
                },
              ],
              pageIndex: 1,
              pageSize: 100,
            },
          })
          .then((res) => {
            
            if ( res.datas.totalCount > 0) {
              const dataArray = res.datas.data;
              const hotelMap = this.hotelList.reduce((acc, hotel) => {
                if (dataArray.filter((d) => d.hotelCode === hotel.code).length > 0) {
                  const key = hotel.hpositionName;
                  if (!acc[key]) {
                    acc[key] = [];
                  }
                  acc[key] = acc[key].concat(dataArray.filter((d) => d.hotelCode === hotel.code));
                }
                return acc;
              }, {});
            
              let dataList = [];
              Object.keys(hotelMap).forEach((key) => {
                const pDataList = hotelMap[key].map((h) => {
                  return this.wrapData(h);
                });
                dataList = dataList.concat(pDataList);
                // 动态生成初始值对象
                const initialTotals = SUM_FIELDS.reduce(
                  (acc, field) => {
                    acc[field] = 0;
                    return acc;
                  },
                  { hotelName: `${key}酒店小计` }
                );

                const subSum = pDataList.reduce((acc, hotel) => {
                  SUM_FIELDS.forEach((field) => {
                    acc[field] += Number(hotel[field]);
                  });
                  return acc;
                }, initialTotals);

                dataList.push(this.wrapData(subSum));
              });
              console.log('最终处理后的数据列表：', dataList);
              this.dataList = dataList;
            } else {
              this.dataList = [];
            }
            this.loading = false;
          })
          .catch((error) => {
            console.error('获取数据失败：', error);
            this.loading = false;
            this.dataList = [];
          });
      },
      summaryData() {
        let record = {};
        this.dataColumns.forEach((c, index) => {
          const colKey = c.dataIndex;
          if (index === 0) {
            record[colKey] = '合计';
          } else if (SUM_FIELDS.includes(colKey)) {
            record[colKey] = this.dataList.filter((d) => d.hotelName.includes('小计')).reduce((sum, item) => (sum += Number(item[colKey])), 0);
          }
        });
        record = this.wrapData(record);
        this.customRenderData(record, this.dataColumns);
        return [record];
      },
      customRenderData(data, columns) {
        columns.forEach((c) => {
          if (c.customRender) {
            const value = { text: data[c.dataIndex] };
            data[c.dataIndex] = c.customRender(value);
          }
          if (c.children) {
            this.customRenderData(data, c.children);
          }
        });
      },
      wrapData(data) {
        if (!data) return {};

        const {
          hotelName,
          actualCrooms = 0,
          actualSrooms = 0,
          revenue = 0,
          roomRevenue = 0,
          fbRevenue = 0,
          bhRevenue = 0,
          otherRevenue = 0,
          lyearRoomRevenue = 0,
          lyearActualCrooms = 0,
          lyearActualSrooms = 0,
          lyearFbRevenue = 0,
          lyearBhRevenue = 0,
          lyearOtherRevenue = 0,
          lyearRevenue = 0,
        } = data;

        // 计算衍生数据
        const actualPrice = this.safeDivide(roomRevenue, actualSrooms);
        const actualRentRate = this.safeDivide(actualSrooms, actualCrooms);
        const lyearPrice = this.safeDivide(lyearRoomRevenue, lyearActualSrooms);
        const lyearRentRate = this.safeDivide(lyearActualSrooms, lyearActualCrooms);
        const actualPerRevenue = actualPrice * actualRentRate;
        const lyearPerRevenue = lyearPrice * lyearRentRate;

        return {
          key: hotelName, // 添加唯一key
          hotelName,
          actualSrooms: Number(actualSrooms) || 0,
          actualCrooms: Number(actualCrooms) || 0,
          actualRentRate,
          actualPrice,
          actualPerRevenue,
          roomRevenue: Number(roomRevenue) || 0,
          fbRevenue: Number(fbRevenue) || 0,
          bhRevenue: Number(bhRevenue) || 0,
          otherRevenue: Number(otherRevenue) || 0,
          revenue: Number(revenue) || 0,
          lyearActualSrooms: Number(lyearActualSrooms) || 0,
          lyearActualCrooms: Number(lyearActualCrooms) || 0,
          lyearRentRate,
          lyearPrice,
          lyearPerRevenue,
          lyearRoomRevenue: Number(lyearRoomRevenue) || 0,
          lyearFbRevenue: Number(lyearFbRevenue) || 0,
          lyearBhRevenue: Number(lyearBhRevenue) || 0,
          lyearOtherRevenue: Number(lyearOtherRevenue) || 0,
          lyearRevenue: Number(lyearRevenue) || 0,
          diffRentRate: this.diffPercent2Formatter(actualRentRate, lyearRentRate, 0),
          diffPrice: this.diffPercent2Formatter(actualPrice, lyearPrice, 0),
          diffPerRevenue: this.diffPercent2Formatter(actualPerRevenue, lyearPerRevenue, 0),
          diffRoomRevenue: this.diffPercent2Formatter(roomRevenue, lyearRoomRevenue, 0),
          diffFbRevenue: this.diffPercent2Formatter(fbRevenue, lyearFbRevenue, 0),
          diffBhRevenue: this.diffPercent2Formatter(bhRevenue, lyearBhRevenue, 0),
          diffOtherRevenue: this.diffPercent2Formatter(otherRevenue, lyearOtherRevenue, 0),
          diffRevenue: this.diffPercent2Formatter(revenue, lyearRevenue, 0),
        };
      },
      handleSearch() {
        this.fetchBaseInfo();
      },
      handleReset() {
        this.currentRange = [this.previousThursday(), this.lastThursday()];
        this.isDetail = false;
        this.fetchBaseInfo();
      },
      checkTag(key) {
        return key.includes('小计');
      },
      getDataColumns() {
        let columns = this.dataColumns;
        if (!this.isDetail) {
          columns = columns.filter((c) => !DETAIL_COLS.includes(c.dataIndex));
        }
        return columns;
      },
      getExportHeader() {
        let exportHeader = this.exportHeader;
        if (!this.isDetail) {
          exportHeader = exportHeader.map((row) =>
            row.filter((_, index) => ![1, 2, 5, 6, 7, 8, 9, 11, 12, 15, 16, 17, 18, 19, 23, 25, 24, 26, 27].includes(index))
          );
          exportHeader[0][1] = '本周实际';
          exportHeader[0][4] = '去年同期';
          exportHeader[0][7] = '差异';
        }
        return exportHeader;
      },
      getExprotMerges() {
        return [
          { s: { r: 0, c: 0 }, e: { r: 1, c: 0 } },
          { s: { r: 0, c: 1 }, e: { r: 0, c: this.isDetail ? 10 : 3 } },
          {
            s: { r: 0, c: this.isDetail ? 11 : 4 },
            e: { r: 0, c: this.isDetail ? 20 : 6 },
          },
          {
            s: { r: 0, c: this.isDetail ? 21 : 7 },
            e: { r: 0, c: this.isDetail ? 28 : 9 },
          },
        ];
      },
      percentFormatter(value) {
        return (value * 100).toFixed(0) + '%';
      },
      percentTipFormatter(params) {
        return (
          params[0].axisValue +
          '<br />' +
          params
            .map((p) => {
              return `${p.marker} ${p.seriesName}: ${(p.data * 100).toFixed(0)}%`;
            })
            .join('<br />')
        );
      },
      /**
       * 将数值格式化为带单位的货币格式（万元）
       * @param value 要格式化的数值
       * @param dot 小数点位数，默认2位
       * @param unit 单位，默认"万"
       */
      currencyWFormatter(value, dot = 2, unit = '万') {
        return MathUtil.currencyWFormatter(value, dot, unit);
      },
      /**
       * 将数值格式化为货币格式（不带单位）
       * @param value 要格式化的数值
       * @param dot 小数点位数，默认0位
       */
      currencyWNFormatter(value, dot = 0) {
        return MathUtil.currencyWNFormatter(value, dot);
      },
      /**
       * 将数值格式化为百分比格式
       * @param value 要格式化的数值
       * @param dot 小数点位数，默认2位
       */
      percent2DFormatter(value, dot = 2) {
        return MathUtil.percent2DFormatter(value, dot);
      },
      /**
       * 计算两个数值的差异百分比
       * @param thisData 当前数值
       * @param lastData 对比数值
       * @param dot 小数点位数，默认2位
       */
      diffPercent2Formatter(thisData, lastData, dot = 2) {
        return MathUtil.diffPercent2Formatter(thisData, lastData, dot);
      },
      /**
       * 将数值格式化为指定小数位数
       * @param value 要格式化的数值
       * @param dot 小数点位数，默认2位
       */
      dot2Formatter(value, dot = 2) {
        return MathUtil.dot2Formatter(value, dot);
      },
      /**
       * 格式化日期范围
       * @param dataRange 日期范围数组
       */
      dateRangeFormatter(dataRange) {
        return DateUtil.dateRangeFormatter(dataRange);
      },
      /**
       * 格式化日期
       * @param data 日期对象
       */
      dateFormatter(data) {
        return DateUtil.dateFormatter(data);
      },
      /**
       * 格式化月份
       * @param data 日期对象
       */
      monthFormatter(data) {
        return DateUtil.monthFormatter(data);
      },
      /**
       * 安全除法运算，避免除数为0的情况
       * @param numerator 被除数
       * @param denominator 除数
       */
      safeDivide(numerator, denominator) {
        return MathUtil.safeDivide(numerator, denominator);
      },
      /**
       * 获取本周或上周的周四日期
       * 如果当前日期是周四之后，返回本周四
       * 如果当前日期是周四之前，返回上周四
       */
      lastThursday() {
        let currentDate = dayjs();
        return currentDate.day(currentDate.day() > 4 ? 4 : -3);
      },
      /**
       * 获取上周四的日期
       * 基于lastThursday()的结果，往前推7天
       */
      previousThursday() {
        return dayjs(this.lastThursday()).subtract(7, 'days');
      },
      handleAccChange(type) {
        this.currentAcc = type;
        let start, end;
        if (type === 'day') {
          start = end = dayjs();
        } else if (type === 'month') {
          start = dayjs().startOf('month');
          end = dayjs().endOf('month');
        } else if (type === 'year') {
          start = dayjs().startOf('year');
          end = dayjs().endOf('year');
        }
        this.currentRange = [start, end];
        this.fetchBaseInfo();
      },
      handleExport() {
        // 1. 获取表头
        const header = this.getExportHeader(); // 二维数组
        // 2. 获取数据
        const data = this.dataList.map(item => {
          // 按照表头顺序组织数据
          // 你可以根据 isDetail 动态调整字段
          if (!this.isDetail) {
            return [
              item.hotelName,
              item.actualRentRate,
              item.actualPrice,
              item.revenue,
              item.lyearRentRate,
              item.lyearPrice,
              item.lyearRevenue,
              item.diffRentRate,
              item.diffPrice,
              item.diffRevenue,
            ];
          } else {
            return [
              item.hotelName,
              item.actualSrooms,
              item.actualCrooms,
              item.actualRentRate,
              item.actualPrice,
              item.actualPerRevenue,
              item.roomRevenue,
              item.fbRevenue,
              item.bhRevenue,
              item.otherRevenue,
              item.revenue,
              item.lyearActualSrooms,
              item.lyearActualCrooms,
              item.lyearRentRate,
              item.lyearPrice,
              item.lyearPerRevenue,
              item.lyearRoomRevenue,
              item.lyearFbRevenue,
              item.lyearBhRevenue,
              item.lyearOtherRevenue,
              item.lyearRevenue,
              item.diffRentRate,
              item.diffPrice,
              item.diffPerRevenue,
              item.diffRoomRevenue,
              item.diffFbRevenue,
              item.diffBhRevenue,
              item.diffOtherRevenue,
              item.diffRevenue,
            ];
          }
        });

        // 3. 合并表头和数据
        const aoa = [...header, ...data];

        // 4. 生成 worksheet
        const ws = XLSX.utils.aoa_to_sheet(aoa);

        // 5. 合并单元格
        ws['!merges'] = this.getExprotMerges();

        // 6. 可选：设置样式（如加粗表头）
        header.forEach((row, rowIdx) => {
          row.forEach((cell, colIdx) => {
            const cellRef = XLSX.utils.encode_cell({ r: rowIdx, c: colIdx });
            if (ws[cellRef]) {
              ws[cellRef].s = {
                font: { bold: true },
                alignment: { horizontal: 'center', vertical: 'center' },
              };
            }
          });
        });

        // 7. 导出
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, '周报');
        XLSX.writeFile(wb, '酒店周报.xlsx');
      },
    },
  };
</script>

<style lang="less" scoped>
  .hotel-week-summary {
    display: flex;
    flex-direction: column;
    // height: 100vh;
    background-color: #fff;

    .top-section {
      background: #fff;
      padding: 24px 24px 0;
    }

    .header-wrapper {
      margin-bottom: 24px;

      .title {
        font-size: 18px;
        font-weight: 600;
        color: #1a253b;
        margin: 0;
        padding: 0;
      }
    }

    .form-wrapper {
      margin-bottom: 24px;

      .form-content {
        display: flex;
        align-items: center;
      }

      .form-item {
        flex: 1;
        display: flex;
        align-items: center;
        padding: 0 16px;

        &:first-child {
          padding-left: 0;
          justify-content: flex-end;
        }

        &:last-child {
          padding-right: 0;
        }

        .label {
          margin-right: 12px;
          color: rgba(0, 0, 0, 0.85);
          font-size: 14px;
        }
      }
      .form-item-center {
        justify-content: center;
      }
      .filter-icon-container {
        display: inline-block;
        padding: 4px;
        border-radius: 4px;
        transition: all 0.3s ease;
        margin-left: 10px;
      }

      .icon-screen {
        width: 20px;
        height: 20px;
        cursor: pointer;
        transition: all 0.3s ease;
        object-fit: scale-down;
      }

      .filter-icon-container:hover {
        background-color: #e1ebf9;
      }

      .icon-screen:hover {
        transform: scale(1.1);
        opacity: 0.8;
      }
    }

    .main-content {
      flex: 1;
      background: #e1ebf9;
      padding: 16px 0;
      overflow: auto;
      .card-flex-all {
        height: 100%;
      }
      &-title-custom {
        color: #00b578;
        font-weight: 500;
      }
    }

    @media @desktop {
      .top-content {
        display: flex;
      }
      .card-flex-all {
        flex: 1 1 calc(100% - 10px);
      }
      .card-flex {
        flex: 1 1 calc(50% - 10px);
      }
    }

    .card-table-head {
      border: 1px solid #d9d9d9;
      border-radius: 4px;
      text-align: center;
      font-weight: 500;
      font-size: 15px;
      padding: 8px 0 0 0;
      margin-bottom: 8px;
      background: #fafbfc;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      flex-direction: column;
      overflow: visible;
    }
    .card-table-head::after {
      content: '';
      display: block;
      width: 100%;
      height: 8px;
      background: linear-gradient(90deg, #eaeaf1 0%, #e9e7f2 100%); /* 仿图片色带 */
      border-bottom-left-radius: 4px;
      border-bottom-right-radius: 4px;
      margin-top: 8px;
    }
    .card-table-head-remark {
      position: absolute;
      right: 12px;
      top: 50%;
      transform: translateY(-50%);
      z-index: 2;
    }
 

    table th {
      border: 6px solid white;
    }

    .head-layer2 {
      background-color: aliceblue;
    }
    .head-layer2 th {
      border: 6px solid white;
    }

    table tbody tr {
      border-bottom: 1px dotted #d9d9d9;
    }

    .hotel-week-summary table tbody tr td {
      text-align: center !important;
      border-bottom: 2px dashed #444; /* 黑灰色虚线 */
    }

    .table-scroll-x {
      overflow-x: auto;
      width: 100%;
    }

    .fixed-width-table {
      width: 100%;
      table-layout: auto;
      border-spacing: 0;
      border-collapse: separate;
    }

    .fixed-width-table thead tr th {
      position: sticky;
      top: 0;
      z-index: 10;
      padding: 0px 10px;
      background: #E9E7F2; /* 保证有背景色 */
    }

    .table-scroll-x::-webkit-scrollbar {
      height: 12px;           /* 滚动条高度（粗细） */
    }
    .table-scroll-x::-webkit-scrollbar-thumb {
      background: #165dff;    /* 深蓝色 */
      border-radius: 6px;
    }
    .table-scroll-x::-webkit-scrollbar-track {
      background: #e6f0ff;    /* 滚动条轨道浅色，可选 */
      border-radius: 6px;
    }

    /* Firefox */
    .table-scroll-x {
      scrollbar-color: #165dff #e6f0ff;
      scrollbar-width: thick;
    }

    .fixed-width-table .head-layer2 th {
      white-space: nowrap;
    }

    .fixed-table-head {
      position: sticky;
      left: 0;
      z-index: 100 !important;
      background: #E9E7F2;
      text-align: center;
      width: 180px;
  min-width: 180px;
  max-width: 180px;
      box-sizing: border-box;
      // border: 0 !important;
      padding: 0 !important;
      border: 6px solid white;
      margin: 0 !important;
      white-space: normal;
      word-break: break-all;
    }

    .fixed-width-table th,
    .fixed-width-table td {
      box-sizing: border-box;
    }

    .hotel-week-summary .fixed-width-table td {
      text-align: center;
    
      /* 其它样式 */
    }

    .fixed-width-table tbody td {
      position: relative;
      padding-bottom: 8px; /* 给下划线留空间，可根据需要调整 */
    }

    .fixed-width-table tbody td::after {
      content: "";
      display: block;
      position: absolute;
      left: 10%;
      right: 10%;
      bottom: 2px;
      height: 0;
      border-bottom: 2px dashed #cccaca;
      width: 80%;
      margin: 0 auto;
      pointer-events: none;
    }

    .acc-selector {
      display: flex;
      align-items: center;
      gap: 8px;

      .button-icon {
        width: 20px;
        height: 20px;
        cursor: pointer;
        transition: all 0.3s ease;
        object-fit: scale-down;

        &.active {
          transform: scale(1.1);
          opacity: 0.8;
        }
      }
    }

    .acc-title-span {
      color: #bbb;
      font-weight: 550;
      transition: color 0.2s;
      &.active {
        color: #222;
      }
    }
  }
</style>
